﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.WinUI.BaseForm;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.WinUI.MasterData;

namespace ESOL.WinUI.Pur
{
    public partial class frmMaintainSupplier : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public MstSupplierEntity SelectedSupplier { get; set; }

        private List<MstSupplierContactEntity> DeleteList = new List<MstSupplierContactEntity>();
        #endregion

        #region Constructor
        public frmMaintainSupplier()
        {
            InitializeComponent();
            if (SelectedSupplier == null)
            {
                SelectedSupplier = new MstSupplierEntity();
                SelectedSupplier.SupplierId = Guid.NewGuid().ToString();
                SelectedSupplier.Status = "STATUS01";//状态：草稿
            }
        }
        #endregion

        #region Functions
        private void Init()
        {
            BindComboBox();
            SetField();
            ResetField();
        }

        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbCurrency, "CS", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbSupplierType, "SUPPT", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbBank, "BANK", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbAllowProducting, "HAVE", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPaymentType, "PMTT", true);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colATTACHED_TYPE, "SAT", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colCONTACT_LEVEL, "CLEVEL", false);
        }

        private void SetField()
        {
            BindContractGrid();
            if (SelectedSupplier != null)
            {
                txtName.Text = SelectedSupplier.SupplierName;
                txtFullName.Text = SelectedSupplier.SupplierFullName;
                txtCode.Text = SelectedSupplier.SupplierCode;
                if (string.IsNullOrEmpty(txtCode.Text))
                {
                    txtCode.Text = "自动生成";
                }
                txtAddress.Text = SelectedSupplier.Address;
                txtZip.Text = SelectedSupplier.ZipCode;
                txtTelphone.Text = SelectedSupplier.Telephone;
                txtBankAccount.Text = SelectedSupplier.BankAccount;
                txtTaxAccount.Text = SelectedSupplier.TaxAccount;
                cmbStatus.SetSelectedValue(SelectedSupplier.Status);
                cmbCurrency.SetSelectedValue(SelectedSupplier.DefaultCurrency);
                cmbBank.SetSelectedValue(SelectedSupplier.Bank);
                txtRegisteredCaptial.Text = SelectedSupplier.RegisteredCapital.ToString("#0");
                txtLegalRepresentative.Text = SelectedSupplier.LegalPerson;
                listProductScope.Tag = null;
                listProductScope.Items.Clear();
                if (string.IsNullOrEmpty(SelectedSupplier.ProductScope) == false)
                {
                    List<MstCommonItemEntity> list = new List<MstCommonItemEntity>();
                    string[] productTypeIds = SelectedSupplier.ProductScope.Split(';');
                    if (productTypeIds != null && productTypeIds.Length > 0)
                    {
                        for (int i = 0; i < productTypeIds.Length; i++)
                        {
                            MstCommonItemEntity entity = MstCommonItemBs.GetMstCommonItemByCode(productTypeIds[i]);
                            if (entity != null)
                            {
                                list.Add(entity);
                            }
                        }
                    }
                    foreach (MstCommonItemEntity entity in list)
                    {
                        if (entity == null)
                        {
                            continue;
                        }
                        listProductScope.Items.Add(entity.ItemName);
                    }
                    listProductScope.Tag = list;
                }
                txtRegisteredAddress.Text = SelectedSupplier.RegisteredAddress;
                txtQuantitySystem.Text = SelectedSupplier.QuantitySystem;
                cmbAllowProducting.SetSelectedValue(SelectedSupplier.AllowProducting);
                txtWebsiteUrl.Text = SelectedSupplier.WebsiteUrl;
                cmbSupplierType.SetSelectedValue(SelectedSupplier.SupplierType);
                cmbPaymentType.SetSelectedValue(SelectedSupplier.PaymentType);

                SetAttachedGrid();
            }
            else return;
        }

        private void InitAttachedGrid()
        {
            List<MstCommonItemEntity> list = MstCommonItemBs.GetMstCommonItemListByType("SAT");
            if (list == null || list.Count == 0)
            {
                return;
            }
            DataTable dt = new DataTable();
            dt.Columns.Add("ATTACHED_TYPE");
            dt.Columns.Add("FILE_NAME");
            dt.Columns.Add("EXPIRED_DATE", typeof(DateTime));
            dt.Columns.Add("REMARK");
            foreach (MstCommonItemEntity item in list)
            {
                DataRow dr = dt.NewRow();
                dr["ATTACHED_TYPE"] = item.ItemCode;
                dt.Rows.Add(dr);
            }
            gvAttached.DataSource = dt;
        }

        //private void CheckAttachedExpired()
        //{
        //    for (int i = 0; i < gvAttached.Rows.Count; i++)
        //    {
        //        gvAttached.Rows[i].Cells["colEXPIRED_DATE"].Style.ForeColor = Color.Black;
        //        gvAttached.Rows[i].Cells["colEXPIRED_DATE"].Style.SelectionForeColor = Color.Black;
        //        if (gvAttached.Rows[i].Cells["colEXPIRED_DATE"].Value == null || gvAttached.Rows[i].Cells["colEXPIRED_DATE"].Value.ToString() == "")
        //        {
        //            continue;
        //        }
        //        DateTime expiredDate = DateTime.Today.AddYears(10);
        //        try
        //        {
        //            expiredDate = Convert.ToDateTime(gvAttached.Rows[i].Cells["colEXPIRED_DATE"].Value);
        //        }
        //        catch
        //        {
        //            continue;
        //        }
        //        if (expiredDate <= DateTime.Today.AddMonths(1))
        //        {
        //            gvAttached.Rows[i].Cells["colEXPIRED_DATE"].Style.ForeColor = Color.Red;
        //            gvAttached.Rows[i].Cells["colEXPIRED_DATE"].Style.SelectionForeColor = Color.Red;
        //        }
        //    }
        //}

        private void SetAttachedGrid()
        {
            InitAttachedGrid();
            List<MstSupplierAttachedEntity> list = MstSupplierAttachedBs.GetBySupplier(SelectedSupplier.SupplierId);
            if (list == null || list.Count == 0)
            {
                return;
            }
            DataTable dt = gvAttached.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                string itemCode = dr["ATTACHED_TYPE"].ToString();
                MstSupplierAttachedEntity entity = GetAttachedFromList(list, itemCode);
                if (entity != null)
                {
                    dr["FILE_NAME"] = entity.FileName;
                    dr["EXPIRED_DATE"] = entity.ExpiredDate.ToString("yyyy-MM-dd");
                    dr["REMARK"] = entity.Remark;
                }
            }
            //CheckAttachedExpired();
        }

        private MstSupplierAttachedEntity GetAttachedFromList(List<MstSupplierAttachedEntity> list, string itemCode)
        {
            List<MstSupplierAttachedEntity> result = (from entity in list
                                                      where entity.SupplierId == SelectedSupplier.SupplierId
                                                          && entity.AttachedType == itemCode
                                                      select entity).ToList<MstSupplierAttachedEntity>();
            if (result != null && result.Count > 0)
            {
                return result[0];
            }
            return null;
        }

        private void BindContractGrid()
        {
            string supplierId = "";
            if (SelectedSupplier != null)
            {
                supplierId = SelectedSupplier.SupplierId;
            }
            DataSet ds = MstSupplierContactBs.GetDataSetBySupplierId(supplierId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvSupplierContect.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvSupplierContect.DataSource = dt;
            DeleteList = new List<MstSupplierContactEntity>();
        }

        private bool CheckData()
        {
            bool bFlag = true;
            if (string.IsNullOrEmpty(txtName.Text.Trim()))
            {
                MessageBox.Show("供应商名称不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtName.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtFullName.Text.Trim()))
            {
                MessageBox.Show("供应商全名不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtFullName.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtCode.Text.Trim()))
            {
                MessageBox.Show("供应商代码不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtCode.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtTelphone.Text.Trim()))
            {
                MessageBox.Show("移动电话不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtTelphone.Focus();
                return false;
            }

            if (listProductScope.Items.Count == 0)
            {
                MessageBox.Show("供应范围不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                listProductScope.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtRegisteredAddress.Text.Trim()))
            {
                MessageBox.Show("注册地址不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtRegisteredAddress.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(cmbSupplierType.Text.Trim()))
            {
                MessageBox.Show("供应商类型不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cmbSupplierType.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(cmbPaymentType.Text.Trim()))
            {
                MessageBox.Show("结算方式不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cmbPaymentType.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(cmbCurrency.Text.Trim()))
            {
                MessageBox.Show("币种不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cmbCurrency.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtAddress.Text.Trim()))
            {
                MessageBox.Show("发货地址不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtAddress.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtZip.Text.Trim()))
            {
                MessageBox.Show("邮编不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtZip.Focus();
                return false;
            }
            if (cmbSupplierType.SelectedValue.Equals("SUPPT04")==false)
            {
                if (string.IsNullOrEmpty(cmbAllowProducting.Text))
                {
                    MessageBox.Show("生产许可证不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cmbAllowProducting.Focus();
                    return false;
                }
                if (string.IsNullOrEmpty(txtRegisteredCaptial.Text.Trim()))
                {
                    MessageBox.Show("注册资金不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtRegisteredCaptial.Focus();
                    return false;
                }
                if (string.IsNullOrEmpty(txtQuantitySystem.Text.Trim()))
                {
                    MessageBox.Show("质量体系不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtQuantitySystem.Focus();
                    return false;
                }
                if (string.IsNullOrEmpty(txtLegalRepresentative.Text.Trim()))
                {
                    MessageBox.Show("法人代表不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtLegalRepresentative.Focus();
                    return false;
                }
                if (string.IsNullOrEmpty(cmbBank.Text.Trim()))
                {
                    MessageBox.Show("开户银行不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cmbBank.Focus();
                    return false;
                }
                if (string.IsNullOrEmpty(txtTaxAccount.Text.Trim()))
                {
                    MessageBox.Show("税号不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtTaxAccount.Focus();
                    return false;
                }
                if (string.IsNullOrEmpty(txtBankAccount.Text.Trim()))
                {
                    MessageBox.Show("账号不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtBankAccount.Focus();
                    return false;
                }
            }
            if (UICommon.UICommonFunctions.CheckDataGrid(gvSupplierContect) == false)
                return false;
            return bFlag;
        }

        private void SetEntity()
        {
            SelectedSupplier.SupplierName = txtName.Text;
            SelectedSupplier.SupplierFullName = txtFullName.Text;
            SelectedSupplier.SupplierCode = txtCode.Text;
            SelectedSupplier.Address = txtAddress.Text;
            SelectedSupplier.ZipCode = txtZip.Text;
            SelectedSupplier.Telephone = txtTelphone.Text;
            SelectedSupplier.DefaultCurrency = cmbCurrency.SelectedValue.ToString();
            SelectedSupplier.Bank = cmbBank.SelectedValue.ToString();
            SelectedSupplier.BankAccount = txtBankAccount.Text;
            SelectedSupplier.TaxAccount = txtTaxAccount.Text;
            SelectedSupplier.LastModifiedDate = DateTime.Now;
            SelectedSupplier.LastModifiedBy = CommonParameter.CurrentUser.PersonId;

            SelectedSupplier.ProductScope = null;
            if (listProductScope.Tag != null && listProductScope.Tag.GetType() == typeof(List<MstCommonItemEntity>))
            {
                List<MstCommonItemEntity> list = (List<MstCommonItemEntity>)listProductScope.Tag;
                foreach (MstCommonItemEntity entity in list)
                {
                    if (string.IsNullOrEmpty(SelectedSupplier.ProductScope))
                    {
                        SelectedSupplier.ProductScope = entity.ItemCode;
                    }
                    else
                    {
                        SelectedSupplier.ProductScope += ";" + entity.ItemCode;
                    }
                }
            }
            SelectedSupplier.RegisteredCapital = CommonFunctions.ToDecimal(txtRegisteredCaptial.Text);
            SelectedSupplier.LegalPerson = txtLegalRepresentative.Text;

            if (cmbSupplierType.SelectedValue != null && cmbSupplierType.SelectedValue.ToString().Trim() != "")
            {
                SelectedSupplier.SupplierType = cmbSupplierType.SelectedValue.ToString();
            }
            if (cmbAllowProducting.SelectedValue != null && cmbAllowProducting.SelectedValue.ToString().Trim() != "")
            {
                SelectedSupplier.AllowProducting = cmbAllowProducting.SelectedValue.ToString();
            }
            if (cmbPaymentType.SelectedValue != null && cmbPaymentType.SelectedValue.ToString().Trim() != "")
            {
                SelectedSupplier.PaymentType = cmbPaymentType.SelectedValue.ToString();
            }
            SelectedSupplier.RegisteredAddress = txtRegisteredAddress.Text;
            SelectedSupplier.QuantitySystem = txtQuantitySystem.Text;
            SelectedSupplier.WebsiteUrl = txtWebsiteUrl.Text;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                SetEntity();
                if (ThisActionType == ActionType.New)
                {
                    DataTable dt = (DataTable)gvSupplierContect.DataSource;
                    bool isSuccessful = MstSupplierBs.SaveSupplier(true, SelectedSupplier, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    DataTable dt = (DataTable)gvSupplierContect.DataSource;
                    bool isSuccessful = MstSupplierBs.SaveSupplier(false, SelectedSupplier, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private bool AuditReject()
        {
            bool bFlag = false;
            if (SelectedSupplier != null)
            {
                SelectedSupplier.Status = "STATUS04";
                try
                {
                    bFlag = MstSupplierBs.UpdateMstSupplier(SelectedSupplier);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            return bFlag;
        }

        private bool AuditApprove()
        {
            bool bFlag = false;
            if (SelectedSupplier != null)
            {
                SelectedSupplier.Status = "STATUS03";
                try
                {
                    bFlag = MstSupplierBs.UpdateMstSupplier(SelectedSupplier);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            return bFlag;
        }

        private bool UploadAttached(MstSupplierAttachedEntity attached, string fileFullName)
        {
            try
            {
                if (attached != null && string.IsNullOrEmpty(fileFullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        attached.FileName = SelectedSupplier.SupplierCode + "_" + attached.AttachedType + "." + CommonFunctions.GetFileExtension(fileFullName);
                        string path = service.SupplierAttachedPath(SelectedSupplier.SupplierCode);
                        byte[] bytes = CommonFunctions.FileToByte(fileFullName);
                        string errMsg = "";
                        bool result = service.UploadFileNew(bytes, path + "\\" + attached.FileName, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        attached.UploadBy = CommonParameter.CurrentUser.PersonId;
                        attached.UploadDate = DateTime.Now;
                        if (attached.ExpiredDate.ToString("yyyy-MM-dd") == "0001-01-01" || attached.ExpiredDate.ToString("yyyy-MM-dd") == "1900-01-01")
                        {
                            attached.ExpiredDate = DateTime.Today.AddYears(1);
                            attached.Remark = "上传文件：" + attached.FileName;
                            result = MstSupplierAttachedBs.InsertMstSupplierAttached(attached);
                        }
                        else
                        {
                            result = MstSupplierAttachedBs.UpdateMstSupplierAttached(attached);
                        }
                        return result;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private bool DownloadAttached(MstSupplierAttachedEntity attached, string fileFullName)
        {
            try
            {
                if (attached != null && string.IsNullOrEmpty(fileFullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        string errMsg = "";
                        string path = service.SupplierAttachedPath(SelectedSupplier.SupplierCode);
                        byte[] bytes = service.DownloadFileNew(path + "\\" + attached.FileName, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        Image image = CommonFunctions.byteArrayToImage(bytes);
                        image.Save(fileFullName);
                        image.Dispose();
                        return true;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            Init();
            base.OnShown(e);
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_SaveNew()
        {
            if (Save())
            {
                SelectedSupplier = new MstSupplierEntity();
                SetField();
            }
        }

        protected override void Click_Reject()
        {
            if (AuditReject())
            {
                MessageBox.Show("已拒审成功!");
            }
            else MessageBox.Show("拒审失败!");
            this.DialogResult = DialogResult.OK;
        }

        protected override void Click_Approve()
        {
            if (AuditApprove())
            {
                MessageBox.Show("已审核成功!");
            }
            else MessageBox.Show("审核失败!");
            this.DialogResult = DialogResult.OK;
        }

        private void ResetField()
        {
            if (cmbSupplierType.SelectedValue.Equals("SUPPT04"))
            {
                lblLegalRepresentative.ForeColor = Color.Black;
                lblRegisteredCaptial.ForeColor = Color.Black;
                lblQuantitySystem.ForeColor = Color.Black;
                lblAllowProducting.ForeColor = Color.Black;
                lblBank.ForeColor = Color.Black;
                lblTaxAccount.ForeColor = Color.Black;
                lblBankAccount.ForeColor = Color.Black;

                //List<MstCommonItemEntity> list = MstCommonItemBs.GetMstCommonItemListByType("SAT");
                //if (list == null || list.Count == 0)
                //{
                //    return;
                //}
                //if (gvAttached.Rows.Count == 0)
                //{
                //    return;
                //}
                //int nIndex = 0;
                //foreach (MstCommonItemEntity item in list)
                //{
                //    gvAttached.Rows[nIndex].Cells["colATTACHED_TYPE"].Style.ForeColor = Color.Black;
                //    nIndex++;
                //}
            }
            else
            {
                lblLegalRepresentative.ForeColor = Color.Red;
                lblRegisteredCaptial.ForeColor = Color.Red;
                lblQuantitySystem.ForeColor = Color.Red;
                lblAllowProducting.ForeColor = Color.Red;
                lblBank.ForeColor = Color.Red;
                lblTaxAccount.ForeColor = Color.Red;
                lblBankAccount.ForeColor = Color.Red;

                //List<MstCommonItemEntity> list = MstCommonItemBs.GetMstCommonItemListByType("SAT");
                //if (list == null || list.Count == 0)
                //{
                //    return;
                //}
                //if (gvAttached.Rows.Count == 0)
                //{
                //    return;
                //}
                //for (int i = 0; i < gvAttached.Rows.Count; i++)
                //{
                //    if (CommonFunctions.ToInt32(gvAttached.Rows[0].Cells[0].Value.ToString().Replace(list[0].ItemType, "")) >= 3)
                //    {
                //        gvAttached.Rows[i].Cells["colATTACHED_TYPE"].Style.ForeColor = Color.Red;
                //    }
                //}
            }
        }

        private void cmbSupplierType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ResetField();
        }

        private void tsmNew_Click(object sender, EventArgs e)
        {
            if (gvSupplierContect.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvSupplierContect.DataSource;
            DataRow dr = dt.NewRow();
            dr["CONTACT_ID"] = Guid.NewGuid().ToString();
            dr["CONTACT_LEVEL"] = "CLEVEL01";
            dr["SUPPLIER_ID"] = SelectedSupplier.SupplierId;
            dr["LAST_MODIFIED_DATE"] = DateTime.Now;
            dr["LAST_MODIFIED_BY"] = CommonParameter.CurrentUser.PersonId;
            dt.Rows.Add(dr);
        }

        private void tsmDelete_Click(object sender, EventArgs e)
        {
            if (gvSupplierContect.DataSource == null)
            {
                return;
            }
            if (gridView1.GetFocusedRow() != null)
            {
                DataRow dr = gridView1.GetFocusedRow() as DataRow;
                if (dr.RowState != DataRowState.Added)
                {
                    MstSupplierContactEntity entity = new MstSupplierContactEntity(dr);
                    DeleteList.Add(entity);
                }
                DataTable dt = gvSupplierContect.DataSource as DataTable;
                dt.Rows.Remove(dr);
            }
        }

        private void colUpload_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (ThisActionType == ActionType.New)
            {
                MessageBox.Show("请先保存供应商后再上传文件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DataTable dt = gvAttached.DataSource as DataTable;
            string attachedType = dt.Rows[nSelectedIndex]["ATTACHED_TYPE"].ToString();
            MstSupplierAttachedEntity attached = MstSupplierAttachedBs.GetBySupplierAndType(SelectedSupplier.SupplierId, attachedType);
            if (attached == null)
            {
                attached = new MstSupplierAttachedEntity();
                attached.AttachedId = Guid.NewGuid().ToString();
                attached.SupplierId = SelectedSupplier.SupplierId;
                attached.AttachedType = attachedType;
            }
            OpenFileDialog fd = new OpenFileDialog();
            fd.Multiselect = false;
            fd.Filter = "JPG文件|*.jpg|PNG文件|*.png";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = UploadAttached(attached, fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                {
                    MessageBox.Show("上传成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    SetAttachedGrid();
                }
            }
        }

        private void colDownload_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (ThisActionType == ActionType.New)
            {
                MessageBox.Show("请先保存供应商后再下载附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DataTable dt = gvAttached.DataSource as DataTable;
            string attachedType = dt.Rows[nSelectedIndex]["ATTACHED_TYPE"].ToString();
            MstSupplierAttachedEntity attached = MstSupplierAttachedBs.GetBySupplierAndType(SelectedSupplier.SupplierId, attachedType);
            if (attached == null || string.IsNullOrEmpty(attached.FileName))
            {
                MessageBox.Show("没有找到可以下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog fd = new SaveFileDialog();
            fd.FileName = attached.FileName;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = DownloadAttached(attached, fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                {
                    MessageBox.Show("下载成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    SetAttachedGrid();
                }
            }
        }

        private void colSave_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (ThisActionType == ActionType.New)
            {
                MessageBox.Show("请先保存供应商后再保存附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DataTable dt = gvAttached.DataSource as DataTable;
            string attachedType = dt.Rows[nSelectedIndex]["ATTACHED_TYPE"].ToString();
            MstSupplierAttachedEntity attached = MstSupplierAttachedBs.GetBySupplierAndType(SelectedSupplier.SupplierId, attachedType);
            if (attached == null || string.IsNullOrEmpty(attached.FileName))
            {
                MessageBox.Show("请先上传附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (dt.Rows[nSelectedIndex]["EXPIRED_DATE"]!= null)
            {
                try
                {
                    attached.ExpiredDate = Convert.ToDateTime(dt.Rows[nSelectedIndex]["EXPIRED_DATE"].ToString());
                }
                catch
                {
                    MessageBox.Show("请输入正确的时间格式！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            if (dt.Rows[nSelectedIndex]["REMARK"] != null)
            {
                attached.Remark = dt.Rows[nSelectedIndex]["REMARK"].ToString();
            }
            if (MstSupplierAttachedBs.UpdateMstSupplierAttached(attached))
            {
                MessageBox.Show("保存成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //CheckAttachedExpired();
            }
            else
            {
                MessageBox.Show("保存失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle > 1)
            {
                e.Appearance.ForeColor = Color.Red;
            }
        }

        int nSelectedIndex;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0 || e.FocusedRowHandle == 0)
                return;
            nSelectedIndex = e.FocusedRowHandle;
        }

        private void btnScopeQuery_Click(object sender, EventArgs e)
        {
            frmMaintainCommonItemQuery frm = new frmMaintainCommonItemQuery("SSCOPE", true);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedCommonItemList != null)
            {
                listProductScope.Tag = frm.SelectedCommonItemList;
                listProductScope.Items.Clear();
                foreach (MstCommonItemEntity entity in frm.SelectedCommonItemList)
                {
                    if (entity == null)
                    {
                        continue;
                    }
                    listProductScope.Items.Add(entity.ItemName);
                }
            }
            else
            {
                listProductScope.Items.Clear();
                listProductScope.Tag = null;
            }
        }
        #endregion
    }
}
